/**********************************************************
 * ThemeManagerAction.java.java
 * Created by Ashutosh
 * Last modified Date: Sep 18, 2008 10:50:34 AM by Ashutosh
 * Revision: <svn revision #>
 * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 **********************************************************/

package com.printeverywhere.action;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.struts2.util.ServletContextAware;

import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.delegator.TranslationSystemServiceDelegator;
import com.printeverywhere.dto.Languages;
import com.printeverywhere.dto.ThemeManager;
import com.printeverywhere.util.FileUtil;
import com.printeverywhere.util.SearchCriteria;

/**
 * The Class ThemeManagerAction.
 */
public class ThemeManagerAction  extends AdminLayoutIntegration implements ServletContextAware {

	/** Logger for this class. */
	private static final Logger logger = Logger.getLogger(ThemeManagerAction.class);

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	private ServletContext servletContext;

	private List<ThemeManager> themeManagerList;

	private List<Languages> languagesList;

	private Map<String, Languages> languagesMap = new HashMap<String, Languages>();

	private ThemeManager themeManager;

	private String copyFrom;

	private String newThemeName;

	SearchCriteria searchCriteria = new SearchCriteria();

	public String getCopyFrom() {
		return copyFrom;
	}

	public void setCopyFrom(String copyFrom) {
		this.copyFrom = copyFrom;
	}

	public List<ThemeManager> getThemeManagerList() {
		return themeManagerList;
	}

	public void setThemeManagerList(List<ThemeManager> themeManagerList) {
		this.themeManagerList = themeManagerList;
	}

	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	public String execute() throws Exception{
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - start"); //$NON-NLS-1$
		}

		themeManagerList = (List<ThemeManager>) CommonFunctionDelegator.getAllfromtable(ThemeManager.class.getName());
		languagesList = TranslationSystemServiceDelegator.getList();

		for (Languages languages : languagesList) {
			this.languagesMap.put(languages.getLanguageCode(), new Languages());
		}

		if (logger.isDebugEnabled()) {
			logger.debug("execute() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	public String createNewTheme() throws Exception{
		if (logger.isDebugEnabled()) {
			logger.debug("createNewTheme() - start"); //$NON-NLS-1$
		}
		if(newThemeName == null || newThemeName.equals("")){
			themeManagerList = (List<ThemeManager>) CommonFunctionDelegator.getAllfromtable(ThemeManager.class.getName());
			languagesList = TranslationSystemServiceDelegator.getList();
			addActionError("Enter new theme name");
			return INPUT;
		}

		if(newThemeName.length() > 50){
			themeManagerList = (List<ThemeManager>) CommonFunctionDelegator.getAllfromtable(ThemeManager.class.getName());
			languagesList = TranslationSystemServiceDelegator.getList();
			addActionError("Theme name not allow more than 50 Character ");
			return INPUT;
		}
		
		Pattern pattern = null;
		pattern = Pattern.compile("^[a-zA-Z0-9]+[a-zA-Z0-9 ]*$");
		Matcher fit = pattern.matcher(newThemeName);
		if(!fit.matches()){
			themeManagerList = (List<ThemeManager>) CommonFunctionDelegator.getAllfromtable(ThemeManager.class.getName());
			languagesList = TranslationSystemServiceDelegator.getList();
			addActionError("Theme name contains only alphanumeric");
			return INPUT;
		}

		searchCriteria.removeAllAttribute();
		searchCriteria.setAttribute("floderName", newThemeName);
		List<ThemeManager> manager = (List<ThemeManager>) CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, ThemeManager.class);
		themeManager = manager.size() > 0 ? manager.get(0) : null;
		if(themeManager != null){
				themeManagerList = (List<ThemeManager>) CommonFunctionDelegator.getAllfromtable(ThemeManager.class.getName());
				languagesList = TranslationSystemServiceDelegator.getList();
				addActionError("Theme with this name is already exist");
				return INPUT;
		}

		String sourcePath=null;
		String destPath = null;

		if(copyFrom.equalsIgnoreCase("front")){
			sourcePath = servletContext.getRealPath("jsp")+"/"+copyFrom;
		}else{
			sourcePath = servletContext.getRealPath("jsp")+"/"+"front/"+copyFrom;
		}

		destPath = servletContext.getRealPath("jsp")+"/"+"front/"+newThemeName;
		File sourceDir = new File(sourcePath);
		File destDir = new File(destPath);


		String panelsPath = servletContext.getRealPath("panels");
		String panelsDestPath = panelsPath+"/"+newThemeName;

		File panelsDir = new File(panelsPath);
		File panelsDestDir = new File(panelsDestPath);
		try{
			FileUtil.copyDirectory(sourceDir, destDir);
			FileUtil.copyDirectory(panelsDir, panelsDestDir);
			themeManager = new ThemeManager();
			themeManager.setFloderName(newThemeName);
			themeManager.setThemeName(newThemeName);
			CommonFunctionDelegator.generalInsertbyobj(themeManager);
		}catch (Exception e) {
			e.printStackTrace();
			themeManagerList = (List<ThemeManager>) CommonFunctionDelegator.getAllfromtable(ThemeManager.class.getName());
			languagesList = TranslationSystemServiceDelegator.getList();
			return INPUT;
		}
		themeManagerList = (List<ThemeManager>) CommonFunctionDelegator.getAllfromtable(ThemeManager.class.getName());
		if (logger.isDebugEnabled()) {
			logger.debug("createNewTheme() - end"); //$NON-NLS-1$
		}
		addActionMessage("New theme added successfully");
		return SUCCESS;
	}

	public String deleteTheme() throws Exception{
		if (logger.isDebugEnabled()) {
			logger.debug("deleteTheme() - start"); //$NON-NLS-1$
		}

		if(copyFrom.equalsIgnoreCase("front")){
			themeManagerList = (List<ThemeManager>) CommonFunctionDelegator.getAllfromtable(ThemeManager.class.getName());
			languagesList = TranslationSystemServiceDelegator.getList();
			addActionError("Default theam can not be deleted");
			return INPUT;
		}

		searchCriteria.removeAllAttribute();
		searchCriteria.setAttribute("floderName", copyFrom);
		List<ThemeManager> manager = (List<ThemeManager>) CommonFunctionDelegator.getObjectBySearchCriteria(searchCriteria, ThemeManager.class);
		themeManager = manager.size() > 0 ? manager.get(0) : null;
		if(themeManager != null){
			try{
			CommonFunctionDelegator.GeneralDelete(themeManager);
			String sourcePath = servletContext.getRealPath("jsp")+"/front/"+copyFrom;
			File dirPath = new File(sourcePath);
			FileUtil.deleteFile(dirPath);
			String panelsPath = servletContext.getRealPath("panels");
			String panelsDestPath = panelsPath+"/"+copyFrom;
			File panelsDestDir = new File(panelsDestPath);
			FileUtil.deleteFile(panelsDestDir);
			}catch (Exception e) {
				themeManagerList = (List<ThemeManager>) CommonFunctionDelegator.getAllfromtable(ThemeManager.class.getName());
				languagesList = TranslationSystemServiceDelegator.getList();
				addActionError("You can not delete this theme");
				return INPUT;
			}
		}

		if (logger.isDebugEnabled()) {
			logger.debug("deleteTheme() - end"); //$NON-NLS-1$
		}
		addActionMessage("Theam has been deleted successfully");
		return SUCCESS;
	}

	public String assignTheme() throws Exception{
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - start"); //$NON-NLS-1$
		}
		if(languagesMap != null){
			for (Languages languages : this.languagesMap.values()) {
				Languages tmpLanguage = new Languages();
				tmpLanguage.setLanguageCode(languages.getLanguageCode());
				tmpLanguage.setLanguageName(languages.getLanguageName());
				tmpLanguage.setActive(languages.getActive());
				tmpLanguage.setDefault_(languages.getDefault_());
				tmpLanguage.setText(languages.getText());
				tmpLanguage.setChromeCss(languages.getChromeCss());
				tmpLanguage.setThemeId(languages.getThemeId());
				CommonFunctionDelegator.generalUpdatebyobj(tmpLanguage);
			}
		}
		addActionMessage("Themes assign to languages successfully");
		return SUCCESS;
	}

	public String getNewThemeName() {
		return newThemeName;
	}

	public void setNewThemeName(String newThemeName) {
		this.newThemeName = newThemeName;
	}

	public ThemeManager getThemeManager() {
		return themeManager;
	}

	public void setThemeManager(ThemeManager themeManager) {
		this.themeManager = themeManager;
	}

	public List<Languages> getLanguagesList() {
		return languagesList;
	}

	public void setLanguagesList(List<Languages> languagesList) {
		this.languagesList = languagesList;
	}

	public Map<String, Languages> getLanguagesMap() {
		return languagesMap;
	}

	public void setLanguagesMap(Map<String, Languages> languagesMap) {
		this.languagesMap = languagesMap;
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	public static void main(String[] args) {
		Pattern pattern = null;
		pattern = Pattern.compile("^[a-zA-Z0-9]+[a-zA-Z0-9 ]*$");
		Matcher fit = pattern.matcher("4564dgvd fasa53454");
		if(fit.matches()){
			System.out.println("pattern correct");
		}else{
			System.out.println("pattern is not correct");
		}

	}

}